package com.user.test.model.database

import android.annotation.SuppressLint
import android.app.Application
import android.util.Log
import androidx.lifecycle.LiveData
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Action
import io.reactivex.schedulers.Schedulers

class SearchResultRepository( application: Application) {
    val database = SearchResultDatabase.getInstance(application)
    val dao = database.searchResultDao()

    @SuppressLint("CheckResult")
    fun insert(searchResult: SearchResult) {
        Completable.fromAction(Action {
            kotlin.run {
                dao.insert(searchResult)
            }
        }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                Log.e("Repo:", "complete insert")
            }
    }

    @SuppressLint("CheckResult")
    fun insertListSearchResult(searchResult: List<SearchResult>) {
        Completable.fromAction(Action {
            kotlin.run {
                dao.insertAll(searchResult)
            }
        }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                Log.e("Repo:", "complete insertAll")
            }
    }

    @SuppressLint("CheckResult")
    fun delete(searchResult: SearchResult) {
        Completable.fromAction(Action {
            kotlin.run {
                dao.delete(searchResult)
            }
        }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                Log.e("Repo:", "complete delete")
            }
    }

    @SuppressLint("CheckResult")
    fun update(searchResult: SearchResult) {
        Completable.fromAction(Action {
            kotlin.run {
                dao.update(searchResult)
            }
        }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                Log.e("Repo:", "complete update")
            }
    }

    @SuppressLint("CheckResult")
    fun getListSearchResults(): LiveData<List<SearchResult>> {
        return dao.getAll()
    }


    /*
    suspend fun getById(id:Int) : {
        dao.getById(id)
    }
 */
    //api key { AIzaSyD0hMA1_QQeIq_DjTBaS618f8ngx0ciqM8 }
}